package cn.itsource.pet.service.impl;

import cn.itsource.basic.util.BaiduAuditUtils;
import cn.itsource.pet.domain.Pet;
import cn.itsource.pet.domain.PetDetail;
import cn.itsource.pet.mapper.PetDetailMapper;
import cn.itsource.pet.mapper.PetMapper;
import cn.itsource.pet.service.IPetService;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.util.resources.cldr.ig.CalendarData_ig_NG;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itsource
 * @since 2022-08-18
 */
@Service
public class PetServiceImpl extends BaseServiceImpl<Pet> implements IPetService {
    @Autowired
    private PetMapper petMapper;

    @Autowired
    private PetDetailMapper petDetailMapper;

    @Override
    public void add(Pet pet) {
        //添加时初始化 为下架状态
        pet.setState(0);
        //初始化 宠物的创建时间
        pet.setCreatetime(new Date());
        //保存pet
        petMapper.add(pet);
        System.out.println(pet);
        //保存detail
        pet.getDetail().setPetId(pet.getId());
        petDetailMapper.add(pet.getDetail());
    }

    /**
     * 批量上架
     * @param ids
     */
    @Override
    public void onsale(List<Long> ids) {
        for (Long id : ids) {
            Boolean flag = true;
            //获取每一个pet
            Pet pet = petMapper.loadOne(id);
            if(!BaiduAuditUtils.TextCensor(pet.getName())){
                //当名字不合法的时候将flag定义为false
                flag = false;
            }

            //如果名字都合格才执行校验图片操作
            if(flag){
                //依次拿到图片的地址
                String[] urls = pet.getResources().split(",");
                //非空校验
                if(urls != null){
                    for (String url : urls) {
                        if(!BaiduAuditUtils.ImgCensor("http://123.207.27.208"+url)){
                            flag = false;
                        }
                    }
                }
            }

            if(flag){
                //如果名字和图片都合法 ①保存审核日志为审核成功 和更新状态为上架
                pet.setNote("审核成功");
                pet.setState(1);
                pet.setOnsaletime(new Date());
                petMapper.update(pet);
            }else {
                pet.setNote("名字或者图片错误!");
                petMapper.update(pet);
            }

        }

    }

    /**
     * 批量下架
     * @param ids
     */
    @Override
    public void offsale(List<Long> ids) {
        for (Long id : ids) {
            Pet pet = petMapper.loadOne(id);
            pet.setState(0);
            pet.setOffsaletime(new Date());
            petMapper.update(pet);
        }
    }
}
